using RabbitMQ.Client;

namespace Beauty.Net.RabbitMQ.Routing
{
    /// <summary>
    /// 路由模式生产者
    /// </summary>
    public class RoutingProducer : RabbitMQProducerBase
    {
        public RoutingProducer(IRabbitMQConnectionManager connectionManager)
            : base(connectionManager)
        {}

        /// <summary>
        /// 发送消息（带路由键）
        /// </summary>
        public void Send<T>(string exchangeName, string routingKey, T message, bool persistent = true)
        {
            using (var channel = _connectionManager.CreateChannel())
            {
                // 声明直接交换机
                channel.ExchangeDeclare(exchange: exchangeName,
                                     type: ExchangeType.Direct,
                                     durable: true,
                                     autoDelete: false,
                                     arguments: null);

                var properties = channel.CreateBasicProperties();
                properties.Persistent = persistent;

                var messageBody = System.Text.Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(message, _jsonOptions));
                channel.BasicPublish(exchange: exchangeName, routingKey: routingKey, basicProperties: properties, body: messageBody);
            }
        }
    }
}